home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / totem / plugins / opensubtitles / hash.py next >
Encoding:
Python Source  |  2009-04-14  |  1.3 KB  |  48 lines

  1. import struct
  2. import os
  3. import gio
  4.  
  5. SIZE_ERROR = -1
  6. SEEK_ERROR = -2
  7.  
  8. def hashFile(name):
  9.        """ FIXME Need to handle exceptions !! """
  10.  
  11.  
  12.        longlongformat = 'q'  # long long 
  13.        bytesize = struct.calcsize(longlongformat) 
  14.            
  15.        fp = gio.File(name) 
  16.            
  17.        filesize = fp.query_info('standard::size', 0).get_attribute_uint64('standard::size') 
  18.        
  19.        hash = filesize 
  20.           
  21.        if filesize < 65536 * 2: 
  22.               return SIZE_ERROR, 0
  23.  
  24.        data = fp.read()                 
  25.        
  26.        if data.can_seek() != True:
  27.                return SEEK_ERROR, 0
  28.  
  29.        for x in range(65536/bytesize):
  30.                buffer = data.read(bytesize)
  31.                (l_value,)= struct.unpack(longlongformat, buffer)  
  32.                hash += l_value 
  33.                hash = hash & 0xFFFFFFFFFFFFFFFF #to remain as 64bit number  
  34.                
  35.        if data.seek(max(0,filesize-65536),1) != True:
  36.                return SEEK_ERROR, 0
  37.  
  38.        for x in range(65536/bytesize):
  39.                buffer = data.read(bytesize)
  40.                (l_value,)= struct.unpack(longlongformat, buffer)  
  41.                hash += l_value 
  42.                hash = hash & 0xFFFFFFFFFFFFFFFF 
  43.         
  44.        data.close() 
  45.        returnedhash =  "%016x" % hash 
  46.        return returnedhash, filesize 
  47.  
  48.